<?php

namespace App\Http\Controllers\Api\Web;

use App\Http\Controllers\Common\ApiController;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use App\Models\User\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoginController extends ApiController {




    /**
     * pc-公众号二维码登录
     * @param Request $request
     * @Date 2022/11/20 23:35
     * @Author Rudy
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request) {
        $config = config('wechat.default');
        $app = Factory::officialAccount($config);
        $key = rand(1000,9999);
        $result = $app->qrcode->temporary("act1_".$key, 1 * 24 * 3600);
        $ticket = $result['ticket'];
        $qrcodeUrl = $app->qrcode->url($ticket);
        return responseSuccess(compact('qrcodeUrl','key'));
    }

    public function phoneLogin(Request $request){

        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'pwd'=>'required',
        ]);

        $phone = $request->input('phone');
        $pwd = md5($request->input('pwd'));


        if(!User::where(compact('phone'))->exists()){
            return responseFail('首次使用手机登录请先微信扫码登录！',[],false,[],401);
        }

        $user = User::where(compact('phone','pwd'))->first();
        if(empty($user)){
            return responseFail('未查找到该用户，账号密码错误！');
        }


        $user->token = createNewToken($user->id, 'pc');
        return responseSuccess($user->toArray(),0,'成功！');


    }

    /**
     * pc-微信开放平台登录
     * @param Request $request
     * @Date 2022/11/20 23:36
     * @Author Rudy
     */
    public function wxOpenLogin(Request $request){
        $from = $request->header('from');
        $this->validate($request, ['code'=>'required']);


        $code = $request->input('code');
        $fromUrl = $request->input('fromUrl','lyxinxiangyi');

        Log::info('wxOpenLogin',[$request->header()]);

        if($from==Constant::FROM_CODE){
            //1.副网站用的exchangeCode，如果请求中带用exchangeCode参数，那说明是付网站来的请求
            $appid = env('WX_OPNE_SITE_XIEYIWENHUI_APPID');
            $secret = env('WX_OPNE_SITE_XIEYIWENHUI_APPSECRET');
        }else{
            //因为主网站是lyxinxianyi和ctbsc共用，但是登录的二维码需要用不同的wxappid，fromUrl用来区分是用哪个网址访问
            if($fromUrl=='ctbsc'){
                $appid = env('WX_OPNE_SITE_CTBWK_APPID');
                $secret = env('WX_OPNE_SITE_CTBWK_APPSECRET');
            }else{
                $appid = env('WX_OPNE_SITE_APPID');
                $secret = env('WX_OPNE_SITE_APPSECRET');
            }
        }

        //Log::info('env',compact('appid','secret','code'));

        if(is_array($code)){
            $code = Arr::last($code);
        }

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        Log::info('url',compact('url'));
        //Log::info('mak',[makeRequest($url)]);
        $strInfo =  makeRequest($url)['result'];
        //Log::info('strInfo',[$strInfo]);
        $info = json_decode($strInfo,true);
        //Log::info('info',[$info]);
        if(isset($info['access_token'])){
            $openid = $info['openid'];
            $access_token = $info['access_token'];

            $urlUser = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
            $strUser =  makeRequest($urlUser)['result'];
            //Log::info('strUser',[$strUser]);
            $user = json_decode($strUser,true);
            //Log::info('user',[$user]);
            if(isset($user['openid'])){
                $nick_name = $user['nickname'];
                $avatar = $user['headimgurl'];
                $union_id = $user['unionid'];
                //$user = User::updateOrCreate(['open_id'=>$openid],compact('nick_name','avatar','union_id'));
                $user = User::updateOrCreate(['union_id'=>$union_id],compact('nick_name','avatar','union_id'));
                $user->token = createNewToken($user->id, 'pc');

                $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])->pluck('item_desc','key')->toArray();
                if($user->is_member==1){
                    //$type = $user->getMemberType()->type??'';
                    $type = $user->type;
                    $user->member_type = $type;
                    $user->member_type_name = $mapMemberType[$type]??'普通用户';
                }else{
                    $user->member_type = 0;
                    $user->member_type_name = '普通用户';
                }

                return responseSuccess($user->toArray());
            }else{
                return responseFail('获取用户信息失败!');
            }
        }else{
            return responseFail('获取access_token失败!');
        }
    }

    public function isLogin(Request $request) {
        $key = $request->input('key');
        //Log::info('isLogin',compact('key'));
        $id = Cache::get($key);
        if(empty($id))
            return responseFail();
        else{
            $user = User::where(compact('id'))->first();
            if(empty($user))
                return responseFail('未查到有效用户！');

            $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])->pluck('item_desc','key')->toArray();
            if($user->is_member==1){
                $type = $user->type;
                //$type = $user->getMemberType()->type??'';
                $user->member_type = $type;
                $user->member_type_name = $mapMemberType[$type]??'普通用户';
            }else{
                $user->member_type = 0;
                $user->member_type_name = '普通用户';
            }

            $user->token = createNewToken($user->id, 'pc');

            /*DB::table('login_log')->insert([
                'user_id'=>$user->id,
                'last_login_time'=>date('Y-m-d H:i:s'),
                'device'=>'pc'
            ]);*/

            return responseSuccess(compact('user'));
        }
    }

    public function suggest(Request $request){
        $content = $request->input('content');

        DB::table('suggest')->insert([
            'content'=>$content,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s')
        ]);
        return responseSuccess([],0,'提交成功，感谢您的建议！');
    }


}
